package com.nyist.myticket.core.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nyist.myticket.core.factory.GenerateCodeFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author yangxiaogen
 * @date 2020/12/29 14:29
 */
public class GetWeather {

    private static Logger logger = LoggerFactory.getLogger(GetWeather.class);

    //private String url = "https://restapi.amap.com/v3/weather/weatherInfo?city=110101&key=<用户key>";
    private String baseUrl = "https://restapi.amap.com/v3/weather/weatherInfo?";
    private String key = GenerateCodeFactory.GAODE_KEY;
    //private String url = baseUrl+"city="+city+"&key="+key;

    public Map<String, Object> getConnect(String city){
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("city", city);
        paramMap.put("key", key);
        String body = HttpUtil.get(baseUrl, paramMap);
        JSONObject jsonObject = JSON.parseObject(body);

        logger.info(jsonObject.toJSONString());

        Object infocode = jsonObject.get("infocode");

        if (!"10000".equals(infocode.toString())) {
            logger.error("获取天气信息失败!!!!!!!");
        }
        JSONArray jsonArray = jsonObject.getJSONArray("lives");
        JSONObject arrayJSONObject = jsonArray.getJSONObject(0);

        // 城市名称
        String youCity = arrayJSONObject.getString("city");
        // 天气情况
        String weather = arrayJSONObject.getString("weather");
        // 当前温度
        String temperature = arrayJSONObject.getString("temperature");
        // 当前风力
        String windpower = arrayJSONObject.getString("windpower");
        // 获取时间
        String reporttime = arrayJSONObject.getString("reporttime");

        Map<String, Object> returnMap = new LinkedHashMap<>();
        returnMap.put("您所在的城市",youCity);
        returnMap.put("当前天气为",weather);
        returnMap.put("当前温度为",temperature);
        returnMap.put("当前风力为",windpower);
        returnMap.put("获取时间为",reporttime);
        return returnMap;
    }

}
